package com.jeff.springWebTestNG.persistence.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeff.springWebTestNG.persistence.data.User2;
import com.jeff.springWebTestNG.persistence.ibatis.mapper.IUser2Mapper;
import com.jeff.springWebTestNG.persistence.ibatis.mapper.IUserMapper;
import com.jeff.springWebTestNG.tx.EventTransactionSynchronization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.support.TransactionSynchronizationManager;

//Implementing IGenericMyBatisPersister is required in this case. Because
//user2Mapper is proxy implemented by MyBatis framework, the service inject it
//must also have an interface, which somehow required by Spring
@Service
public class GenericMyBatisPersister implements IGenericMyBatisPersister {
    @Resource
    private IUser2Mapper user2Mapper;

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public void tryDoingSomething() {
            user2Mapper.deleteAll();

            User2 user = new User2();
            user.setName("Rollbacker");
            user.setAddress("Rollback School");
            user2Mapper.addUser(user);

            if (true) {//operations will always rollback, transaction test for Spring+MyBatis success!
                    throw new RuntimeException("Rollback please");
            }
    }

    @Resource
    private IUserMapper userMapper;

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public void tryDoingSth(boolean failIt) {
        System.out.println("in tryDoingSth() isSynchronizationActive = " + 
                TransactionSynchronizationManager.isSynchronizationActive());
        
        TransactionSynchronizationManager.registerSynchronization(new EventTransactionSynchronization());
        
        userMapper.createUser("Jeff312", 12);
        if (failIt) {
            throw new RuntimeException("rollback already");
        }
        System.out.println("Nothing to rollback, ready to commit.");
    }
        
        
}
